package com.jzy.service.impl;

import com.jzy.entity.Vo.RelationshipVoKey;
import com.jzy.repository.RelationshipRepository;
import com.jzy.service.IRelationshipService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class RelationshipServiceImpl implements IRelationshipService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RelationshipServiceImpl.class);

    @Resource
    private RelationshipRepository relationshipRepository;

    //精准 查询文章 标签 中间表数量
    @Override
    public Long countById(Integer cid, Integer mid) {
        LOGGER.debug("Enter countById method:cid={},mid={}", cid, mid);
        Specification<RelationshipVoKey> specification = (Specification<RelationshipVoKey>) (root, query, criteriaBuilder) -> {
            ArrayList<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("cid"), cid));
            predicates.add(criteriaBuilder.equal(root.get("mid"), mid));
            int size = predicates.size();
            return criteriaBuilder.and(predicates.toArray(new Predicate[size]));
        };
        long count = relationshipRepository.count(specification);
        LOGGER.debug("Exit countById method return count={}", count);
        return count;
    }

    @Override
    public void insertVo(RelationshipVoKey relationshipVoKey) {
        relationshipRepository.saveAndFlush(relationshipVoKey);
    }

    //删除 文章 标签 中间表信息
    @Override
    public void deleteById(Integer cid, Integer mid) {
        Specification<RelationshipVoKey> specification = (Specification<RelationshipVoKey>) (root, query, criteriaBuilder) -> {
            ArrayList<Predicate> predicates = new ArrayList<>();
            if (cid != null) {
                predicates.add(criteriaBuilder.equal(root.get("cid"), cid));
            }
            if (mid != null) {
                predicates.add(criteriaBuilder.equal(root.get("mid"), mid));
            }
            int size = predicates.size();
            return criteriaBuilder.and(predicates.toArray(new Predicate[size]));
        };
        List<RelationshipVoKey> all = relationshipRepository.findAll(specification);
        if (all.size() != 0) {
            for (RelationshipVoKey relationshipVoKey : all) {
                relationshipRepository.delete(relationshipVoKey);
            }
        }
    }
}
